<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)" label-align="top">
        <t-form-item label="编号" name="activityAgendaId">
          <t-input v-model="queryParams.activityAgendaId" placeholder="请输入编号" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="议程环节名称" name="agendaName">
          <t-input v-model="queryParams.agendaName" placeholder="请输入议程环节名称" clearable @enter="handleQuery" />
</t-form-item>
        <t-form-item label="议程开始时间">
          <t-date-range-picker
            v-model="dateRangeAgendaStartTime"
            style="width: 240px"
            allow-input
            clearable
            separator="-"
            :placeholder="['开始日期', '结束日期']"
          />
        </t-form-item>
        <t-form-item label="议程结束时间">
          <t-date-range-picker
            v-model="dateRangeAgendaEndTime"
            style="width: 240px"
            allow-input
            clearable
            separator="-"
            :placeholder="['开始日期', '结束日期']"
          />
        </t-form-item>
        <t-form-item label="创建时间">
          <t-date-range-picker
            v-model="dateRangeCreateTime"
            style="width: 240px"
            allow-input
            clearable
            separator="-"
            :placeholder="['开始日期', '结束日期']"
          />
        </t-form-item>
        <t-form-item label-width="0px">
            <t-space align="end" style="height: 64px">
                <t-button theme="primary" @click="handleQuery">
                    <template #icon> <search-icon /></template>
                    搜索
                </t-button>
                <t-button theme="default" @click="resetQuery">
                    <template #icon> <refresh-icon /></template>
                    重置
                </t-button>
            </t-space>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="activityAgendaId"
        :data="activityAgendaList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        :sort="sort"
        show-sort-column-bg-color
        @sort-change="handleSortChange"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xhlj:activityAgenda:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xhlj:activityAgenda:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xhlj:activityAgenda:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xhlj:activityAgenda:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>



        <template #sysUser="{ row }">
            <span v-if="row.sysUser && Object.keys(row.sysUser).length > 1">
              {{ row.sysUser[Object.keys(row.sysUser)[1]] }}（编号为{{ row.sysUser[Object.keys(row.sysUser)[0]] }}）
            </span>
        </template>

        <template #activity="{ row }">
            <span v-if="row.activity && Object.keys(row.activity).length > 1">
              {{ row.activity[Object.keys(row.activity)[1]] }}（编号为{{ row.activity[Object.keys(row.activity)[0]] }}）
            </span>
        </template>




        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link v-hasPermi="['xhlj:activityAgenda:query']" theme="primary" hover="color" @click.stop="handleDetail(row)">
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xhlj:activityAgenda:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link v-hasPermi="['xhlj:activityAgenda:remove']" theme="danger" hover="color" @click.stop="handleDelete(row)">
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>
    <!-- 添加或修改活动议程对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="1100px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="onConfirm"
    >
      <t-loading :loading="buttonLoading">
        <t-form
          ref="activityAgendaRef"
          label-align="top"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >

          <t-form-item label="议程环节名称" name="agendaName">
            <t-textarea v-model="form.agendaName" placeholder="请输入议程环节名称" />
          </t-form-item>

    <t-form-item label="活动" name="activity">
        <t-select v-model="form.activityId" :options="optionsXhljActivity" clearable placeholder="请选择活动">
            <template #panelTopContent>
                <div style="padding: 6px 6px 0 6px">
                    <t-textarea v-model="searchXhljActivity" placeholder="请输入关键词搜索" @change="onSearchXhljActivity" />
                </div>
            </template>
        </t-select>
    </t-form-item>

          <t-form-item label="议程开始时间" name="agendaStartTime">
            <t-date-picker
              v-model="form.agendaStartTime"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择议程开始时间"
            />
          </t-form-item>

          <t-form-item label="议程结束时间" name="agendaEndTime">
            <t-date-picker
              v-model="form.agendaEndTime"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择议程结束时间"
            />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 活动议程详情 -->
    <t-dialog
      v-model:visible="openView"
      header="活动议程详情"
      placement="center"
      width="800px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">

        <t-descriptions-item label="编号">{{ form.activityAgendaId }}</t-descriptions-item>

        <t-descriptions-item label="议程环节名称" :span="2">{{ form.agendaName }}</t-descriptions-item>

        <span v-if="form.sysUser && Object.keys(form.sysUser).length > 1">
              {{ form.sysUser[Object.keys(form.sysUser)[1]] }}（编号为{{ form.sysUser[Object.keys(form.sysUser)[0]] }}）
        </span>

        <span v-if="form.activity && Object.keys(form.activity).length > 1">
              {{ form.activity[Object.keys(form.activity)[1]] }}（编号为{{ form.activity[Object.keys(form.activity)[0]] }}）
        </span>

        <t-descriptions-item label="议程开始时间">{{ parseTime(form.agendaStartTime) }}</t-descriptions-item>

        <t-descriptions-item label="议程结束时间">{{ parseTime(form.agendaEndTime) }}</t-descriptions-item>

        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>

      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'ActivityAgenda',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { SelectProps, TextareaProps, FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext, TableSort } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { XhljActivityAgendaForm, XhljActivityAgendaQuery, XhljActivityAgendaVo } from '@/api/xhlj/model/activityAgendaModel';
import { listActivityAgenda, getActivityAgenda, delActivityAgenda, addActivityAgenda, updateActivityAgenda } from '@/api/xhlj/activityAgenda';
import type { XhljActivityQuery } from '@/api/xhlj/model/activity';
import { listActivity } from '@/api/xhlj/activity';


const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const activityAgendaRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const activityAgendaList = ref<XhljActivityAgendaVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const sort = ref<TableSort>();



const queryParamsXhljActivity = ref<XhljActivityQuery>({
    pageNum: 1,
    pageSize: 10000,
});
const listXhljActivity = [];
const optionsXhljActivity = ref<SelectProps['options']>(listXhljActivity);
const searchXhljActivity = ref('');
const onSearchXhljActivity: TextareaProps['onChange'] = () => {
    optionsXhljActivity.value = listXhljActivity.filter((item) => item.label.indexOf(searchXhljActivity.value) !== -1);
};
/** 查询活动列表 */
function getActivityList() {
    listActivity(queryParamsXhljActivity.value)
        .then((response) => {
            response.rows.forEach((item) => {
                const option: SelectProps = {
                    label: item[Object.keys(item)[1]],
                    value: item[Object.keys(item)[0]],
                };
                listXhljActivity.push(option)
            });
            console.log("XhljActivity", response.rows)
            console.log("listXhljActivity", listXhljActivity)
        })
}

const dateRangeAgendaStartTime = ref([]);

const dateRangeAgendaEndTime = ref([]);

const dateRangeCreateTime = ref([]);


// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `编号`, colKey: 'activityAgendaId', align: 'center', ellipsis: true },
  { title: `议程环节名称`, colKey: 'agendaName', align: 'center', ellipsis: true },
  { title: `系统用户`, colKey: 'sysUser', align: 'center', minWidth: 100, ellipsis: true },
  { title: `活动`, colKey: 'activity', align: 'center', minWidth: 100, ellipsis: true },
  { title: `议程开始时间`, colKey: 'agendaStartTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `议程结束时间`, colKey: 'agendaEndTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `操作`, colKey: 'operation', align: 'center', width: 120 },
]);
// 提交表单对象
const form = ref<XhljActivityAgendaVo & XhljActivityAgendaForm>({});
// 查询对象
const queryParams = ref<XhljActivityAgendaQuery>({
  pageNum: 1,
  pageSize: 10,
  activityAgendaId: undefined,
  agendaName: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询活动议程列表 */
function getList() {
  loading.value = true;
  proxy.addDateRange(queryParams.value, dateRangeAgendaStartTime.value, 'AgendaStartTime');
  proxy.addDateRange(queryParams.value, dateRangeAgendaEndTime.value, 'AgendaEndTime');
  proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  listActivityAgenda(queryParams.value)
    .then((response) => {
      activityAgendaList.value = response.rows;
      total.value = response.total;
      console.log("ActivityAgenda", response.rows)
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('activityAgendaRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeAgendaStartTime.value = [];
  dateRangeAgendaEndTime.value = [];
  dateRangeCreateTime.value = [];
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  handleSortChange(null);
}

/** 排序触发事件 */
function handleSortChange(value?: TableSort) {
  sort.value = value;
  if (Array.isArray(value)) {
    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
  } else {
    queryParams.value.orderByColumn = value?.sortBy;
    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
  }
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加活动议程';
}

/** 详情按钮操作 */
function handleDetail(row: XhljActivityAgendaVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const activityAgendaId = row.activityAgendaId;
  getActivityAgenda(activityAgendaId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XhljActivityAgendaVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改活动议程';
  const activityAgendaId = row?.activityAgendaId || ids.value.at(0);
  getActivityAgenda(activityAgendaId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交按钮 */
function onConfirm() {
  activityAgendaRef.value.submit();
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.activityAgendaId) {
      updateActivityAgenda(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addActivityAgenda(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XhljActivityAgendaVo) {
  const activityAgendaIds = row?.activityAgendaId || ids.value;
  proxy.$modal.confirm(`是否确认删除活动议程编号为${activityAgendaIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delActivityAgenda(activityAgendaIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, activityAgendaIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.addDateRange(queryParams.value, dateRangeAgendaStartTime.value, 'AgendaStartTime');
  proxy.addDateRange(queryParams.value, dateRangeAgendaEndTime.value, 'AgendaEndTime');
  proxy.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime');
  proxy.download(
    'xhlj/activityAgenda/export',
    {
      ...queryParams.value,
    },
    `activityAgenda_${new Date().getTime()}.xlsx`,
  );
}

getList();
getActivityList();
</script>
